package com.boot.main.utils;

import com.alibaba.excel.EasyExcel;
import lombok.SneakyThrows;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

public class FileUtil {
    public static String uploadFile(MultipartFile file, HttpServletRequest request){
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        String path = applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() + "\\ccom-admin-main\\src\\main\\resources\\static\\images\\";
        // System.out.println(applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath());
//        String path = request.getServletContext().getRealPath("/") + "/upload";
        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdir();
        }
        String oldName = file.getOriginalFilename();
        String ext = "." + oldName.split("\\.")[1];
        String uuid = UUID.randomUUID().toString().replace("-","");
        String newName = uuid + ext;
        File file2 = new File(path + newName);
        try {
            file.transferTo(file2);
        }catch (IllegalStateException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return "/images/" + newName;
    }

    @SneakyThrows
    public static void exportExcel(HttpServletResponse response, String name, List list, Class clazz){
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(name).doWrite(list);
    }

    @SneakyThrows
    public static List importExcel(MultipartFile file, Class clazz){
        ColumnListener columnListener = new ColumnListener();
        EasyExcel.read(file.getInputStream(),clazz, columnListener).sheet().doRead();
        List list = columnListener.getList();
        return list;
    }
}
